<!-- 
  Calendar 日历组件                 zls-2022/06/03
    所有属性、事件、方法、插槽，请参考  https://vant-contrib.gitee.io/vant/#/zh-CN/calendar
 -->
<template>
  <Field
    class="z-input"
    v-model="data"
    :name="$attrs['name']"
    :label="$attrs['label']"
    :required="$attrs['required']"
    :rules="$attrs['required'] || $attrs['required'] === '' ? [{ required: true, message: '请选择' }] : []"
    :placeholder="$attrs['placeholder'] || '请选择'"
    :disabled="$attrs['disabled']"
    :readonly="$attrs['readonly'] || true"
    :border="$attrs['border']"
    :colon="$attrs['colon']"
    :clickable="$attrs['clickable']"
    :is-link="$attrs['is-link'] || true"
    :label-width="$attrs['label-width']"
    :autocomplete="$attrs['autocomplete']"
    @click="show = true"
  >
    <template #left-icon>
      <slot name="left-icon"></slot>
    </template>
    <template #right-icon>
      <z-svg name="chahao" v-if="data" @click.stop="clear"></z-svg>
    </template>
    <template #button>
      <slot name="button"></slot>
    </template>
    <template #extra>
      <slot name="extra"></slot>
    </template>
  </Field>
  <Calendar
    v-model:show="show"
    :type="$attrs['type']"
    :title="$attrs['title']"
    :min-date="$attrs['min-date'] || minDate"
    :max-date="$attrs['max-date'] || maxDate"
    :default-date="$attrs['default-date']"
    :row-height="$attrs['row-height']"
    :formatter="$attrs['formatter']"
    :show-confirm="$attrs['show-confirm']"
    :readonly="$attrs['readonly']"
    :first-day-of-week="$attrs['first-day-of-week']"
    :position="$attrs['position']"
    :max-range="$attrs['max-range']"
    :range-prompt="$attrs['range-prompt']"
    :allow-same-day="$attrs['allow-same-day'] || true"
    @confirm="confirm"
  />
</template>

<script>
export default { name: 'z-calendar' }
</script>
<script setup>
import { ref, useAttrs, watch } from 'vue'
import { Field, Calendar } from 'vant'
import $day from 'dayjs'
const emit = defineEmits(['update:modelValue', 'clear', 'confirm'])
const attrs = useAttrs()

const data = ref('')
const show = ref(false) // 是否显示弹框
const minDate = ref(new Date($day().subtract(5, 'year'))) // 最大时间为5年前
const maxDate = ref(new Date($day().add(5, 'year'))) // 最大时间为5年后

watch(
  () => attrs.modelValue,
  newVal => {
    data.value = newVal
  },
  { immediate: true, deep: true }
)

// 清空时间
function clear() {
  emit('update:modelValue', '')
  emit('confirm', '')
  emit('clear', '')
}

// 选中某一项后，点击确认按钮 { value: 前选中的时间 }
function confirm(value) {
  show.value = false
  const time = attrs.type === 'single' ? $day(value).format('YYYY-MM-DD') : value.map(v => $day(v).format('YYYY-MM-DD')).join()
  emit('update:modelValue', time)
  emit('confirm', time)
}
</script>
